package com.guoqing.example.service;

import com.guoqing.example.entity.MyUser;
import com.guoqing.example.entity.Resource;
import com.guoqing.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author ZhangGuoQing
 * @Date 2020/8/21/0021 16:22
 */
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser user = userMapper.selectUserByUserName(username);
        if (Objects.isNull(user)) {
            return null;
        }
        List<Resource> resourceByUsername = userMapper.getResourceByUsername(username);
        if (!resourceByUsername.isEmpty()) {
            List<String> collect = resourceByUsername.stream().map(Resource::getResourceCode).collect(Collectors.toList());
            String[] strings = collect.toArray(new String[resourceByUsername.size()]);
            return User.withUsername(username).password(user.getPwd())
                    .authorities(strings).build();
        }
        return null;
    }
}
